package com.dmooo.yxmmerchant.util;

import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.os.Build;
import android.util.DisplayMetrics;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.common.preimgloader.StartPreViewActivityUtil;
import com.common.util.BaseActivityManager;
import com.common.util.LogUtil;
import com.dmooo.yxmmerchant.common.Config;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class WebViewSettingUtil {
    public static void webSetting(WebView webView) {
        WebSettings settings = webView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setDomStorageEnabled(true);
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);
        webView.setWebViewClient(new MyWebViewClient());
        settings.setBlockNetworkImage(false);//解决图片不显示
        webView.setWebChromeClient(new WebChromeClient());
        if (webView.isHardwareAccelerated()) webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.TEXT_AUTOSIZING);
        } else {
            settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            settings.setMixedContentMode(WebSettings.MIXED_CONTENT_ALWAYS_ALLOW);
        }
        settings.setUseWideViewPort(true);//关键点

        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.SINGLE_COLUMN);

        settings.setDisplayZoomControls(false);
        settings.setJavaScriptEnabled(true); // 设置支持javascript脚本
        settings.setAllowFileAccess(true); // 允许访问文件
        settings.setBuiltInZoomControls(true); // 设置显示缩放按钮
        settings.setSupportZoom(true); // 支持缩放



        settings.setLoadWithOverviewMode(true);

        DisplayMetrics metrics = new DisplayMetrics();
        BaseActivityManager.getInstance().currentActivity().getWindowManager().getDefaultDisplay().getMetrics(metrics);
        int mDensity = metrics.densityDpi;
        if (mDensity == 240) {
            settings.setDefaultZoom(WebSettings.ZoomDensity.FAR);
        } else if (mDensity == 160) {
            settings.setDefaultZoom(WebSettings.ZoomDensity.MEDIUM);
        } else if(mDensity == 120) {
            settings.setDefaultZoom(WebSettings.ZoomDensity.CLOSE);
        }else if(mDensity == DisplayMetrics.DENSITY_XHIGH){
            settings.setDefaultZoom(WebSettings.ZoomDensity.FAR);
        }else if (mDensity == DisplayMetrics.DENSITY_TV){
            settings.setDefaultZoom(WebSettings.ZoomDensity.FAR);
        }else{
            settings.setDefaultZoom(WebSettings.ZoomDensity.MEDIUM);
        }

        settings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NARROW_COLUMNS);
    }
    public static void webSetting(WebView webView, List<String> imageUrls,Context context) {
        webSetting(webView);
        webView.addJavascriptInterface(new MJavascriptInterface(context,imageUrls), "imagelistener");
    }

    /**
     * webview加载富文本数据
     *
     * @param webView
     * @param content
     */
    public static void loadData(WebView webView, String content) {
        String webData = "<html><head><meta name=\"viewport\" content=\"width=device-width,initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no\"/></head><body>" + content + "</body></html>";
        webData = webData.replaceAll("<img", "<img style='width:100%'");
        webData = webData.replaceAll("\"/Public", "\"" + Config.APP_INTERFACE_BASE_URL + "/Public");
        webView.loadData(webData, "text/html;charset=utf-8", "utf-8");
    }
   static class MyWebViewClient extends WebViewClient {
        @Override
        public void onPageFinished(WebView view, String url) {
            view.getSettings().setJavaScriptEnabled(true);
            super.onPageFinished(view, url);
            addImageClickListener(view);//待网页加载完全后设置图片点击的监听方法
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            view.getSettings().setJavaScriptEnabled(true);
            super.onPageStarted(view, url, favicon);
        }

        private void addImageClickListener(WebView webView) {
            LogUtil.d("dsafsd","dsfasdf");
            webView.loadUrl("javascript:(function(){" +
                    "var objs = document.getElementsByTagName(\"img\"); " +
                    "for(var i=0;i<objs.length;i++)  " +
                    "{"
                    + "    objs[i].onclick=function()  " +
                    "    {  "
                    + "        window.imagelistener.openImage(this.src);  " +//通过js代码找到标签为img的代码块，设置点击的监听方法与本地的openImage方法进行连接
                    "    }  " +
                    "}" +
                    "})()");
        }
    }
    /**
     * 得到网页中图片的地址
     */
    public static List<String> getImgStr(String htmlStr) {
        List<String> pics = new ArrayList<>();
        String img = "";
        Pattern p_image;
        Matcher m_image;
        //     String regEx_img = "<img.*src=(.*?)[^>]*?>"; //图片链接地址
        String regEx_img = "<img.*src\\s*=\\s*(.*?)[^>]*?>";
        p_image = Pattern.compile
                (regEx_img, Pattern.CASE_INSENSITIVE);
        m_image = p_image.matcher(htmlStr);
        while (m_image.find()) {
            // 得到<img />数据
            img = m_image.group();
            // 匹配<img>中的src数据
            Matcher m = Pattern.compile("src\\s*=\\s*\"?(.*?)(\"|>|\\s+)").matcher(img);
            while (m.find()) {
                pics.add(m.group(1).contains("http")?m.group(1):(Config.APP_INTERFACE_BASE_URL+m.group(1)));
            }
        }
        System.out.println(pics.size());
        return pics;
    }
    static class MJavascriptInterface {
        private Context context;
        private List<String> imageUrls;

        public MJavascriptInterface(Context context,List<String> imageUrls) {
            this.context = context;
            this.imageUrls = imageUrls;
        }

        @android.webkit.JavascriptInterface
        public void openImage(String img) {
            int posi=0;
            for(int i=0;i<imageUrls.size();i++){
                if(img.equals(imageUrls.get(i))){
                    posi=i;
                    break;
                }
            }
            StartPreViewActivityUtil.startPre(imageUrls, (Activity) context,posi);
//            Intent intent = new Intent();
//            intent.putExtra("imageUrls", imageUrls);
//            intent.putExtra("curImageUrl", img);
//            intent.setClass(context, PhotoBrowserActivity.class);
//            context.startActivity(intent);
        }
    }
}
